package com.fz.us.oa.web.controller.com;

import com.fz.us.admin.base.bean.BaseEnumManager;
import com.fz.us.admin.base.bean.jqgrid.JqGridFilter;
import com.fz.us.admin.base.bean.jqgrid.JqGridPager;
import com.fz.us.admin.base.bean.search.SearchEnum;
import com.fz.us.admin.base.bean.search.order.Order;
import com.fz.us.admin.base.bean.search.result.SearchResultPaging;
import com.fz.us.admin.base.bean.search.rule.Rule;
import com.fz.us.admin.base.bean.search.rule.RuleHelper;
import com.fz.us.admin.company.bean.FlowEnum;
import com.fz.us.admin.company.entity.Company;
import com.fz.us.admin.company.entity.Department;
import com.fz.us.admin.company.entity.TaskEntity;
import com.fz.us.admin.company.entity.User;
import com.fz.us.admin.company.service.DepartmentService;
import com.fz.us.admin.company.service.DutyService;
import com.fz.us.admin.company.service.TaskEntityService;
import com.fz.us.admin.company.service.UserService;
import com.fz.us.oa.core.entity.com.Asset;
import com.fz.us.oa.core.entity.com.AssetUse;
import com.fz.us.oa.core.service.com.AssetService;
import com.fz.us.oa.core.service.com.AssetUseService;
import com.fz.us.oa.core.service.com.PersonnelInfoService;
import com.fz.us.oa.web.controller.BaseController;
import com.fz.us.oa.web.shiro.bind.annotation.CurrentUser;
import com.fz.us.oa.web.spring.bind.annotation.RequestJsonParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by ZhuChunXiao on 2017/7/26.
 */
@Controller
@RequestMapping(value = "/com/assetUse")
public class AssetUseController extends BaseController {
    private static final long serialVersionUID = -7865202671559981510L;

    @Autowired
    private AssetUseService assetUseService;
    @Autowired
    private AssetService assetService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private UserService userService;
    @Autowired
    private PersonnelInfoService personnelInfoService;
    @Autowired
    private DutyService dutyService;
    @Autowired
    private TaskEntityService taskEntityService;


    private Asset asset;
    private Date dateApply;
    private SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy");
    private SimpleDateFormat monthFormat = new SimpleDateFormat("MM");
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    /**
     * 新建，编辑页面
     */
    @RequestMapping(value = "input", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String input(@CurrentUser User user, Model model,String keyId,String draft,String index,String todo,String remind,String record) {
        if (StringUtils.isNotEmpty(keyId)){
            AssetUse assetUse=assetUseService.get(keyId);
            model.addAttribute("keyId", keyId);
            model.addAttribute("assetUse", assetUse);
        }
        model.addAttribute("user", user);
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);
        return "/com/assetuse_input";
    }

    /**
     * 只读页面
     */
    @RequestMapping(value = "read", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String read(@CurrentUser User user, Model model,String keyId,String draft,String index,String todo,String remind,String record) {
        if(StringUtils.isNotEmpty(keyId)) {
            AssetUse assetUse=assetUseService.get(keyId);
            TaskEntity taskEntity = taskEntityService.getInfoByKeyId(keyId);
            int stepNo = taskEntity.getStepNo();
            String isEdit =  isEdit(keyId);
            model.addAttribute("stepNo", stepNo);
            model.addAttribute("isEdit", isEdit);
            model.addAttribute("assetUse", assetUse);
        }

        model.addAttribute("keyId", keyId);
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);
        return "/com/assetuse_read";
    }

    /**
     * 保存Model数据
     */
    private AssetUse saveModel(User user, String keyId, String assetId, String name, String deptId, String userId) throws ParseException {

        AssetUse assetUse = null;
        if (StringUtils.isBlank(keyId)) {
            assetUse = new AssetUse();
            assetUse.setCreater(user);
            assetUse.setCompany(user.getCompany());
        } else {
            assetUse = assetUseService.get(keyId);
        }

        if (StringUtils.isNotBlank(assetId)) {
            Asset asset = assetService.get(assetId);
            if (asset != null) {
                assetUse.setAsset(asset);
            }
        }

        if (StringUtils.isNotBlank(name)) {
            assetUse.setName(name);
        }

        if (StringUtils.isNotBlank(deptId)) {
            Department dept = departmentService.get(deptId);
            if (dept != null) {
                assetUse.setUseDepartment(dept);
            }
        }

        if (StringUtils.isNotBlank(userId)) {
            User user1 = userService.get(userId);
            if (user1 != null) {
                assetUse.setUser(user1);
            }
        }

        if (assetUse.getForm() == null) {
            assetUse.setForm("资产使用登记表");
        }

        return assetUse;
    }

    /**
     * 保存操作
     */
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public Object save(@CurrentUser User user, @RequestParam(required = false) String keyId, String assetId, String name, String deptId, String userId) throws ParseException {

        Map<String,Object> rMap=new HashMap<String,Object>();
        AssetUse assetUse = saveModel(user,keyId,assetId,name,deptId,userId);
        if(StringUtils.isNotEmpty(keyId)){
            assetUseService.update(assetUse);
            rMap.put("message", "更新成功");
        } else {
            assetUseService.save(assetUse, "com.fz.us.oa.core.entity.com.AssetUse");
            rMap.put("message", "保存成功");
        }
        rMap.put("state", "1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    /**
     *提交操作
     */
    @RequestMapping(value = "commit", method = RequestMethod.POST)
    public Object commit(@CurrentUser User user, @RequestParam(required = false) String keyId, String assetId, String name, String deptId, String userId,
                         String curDutyId, String comment) throws ParseException{

        Map<String,Object> rMap=new HashMap<String,Object>();
        AssetUse assetUse = saveModel(user,keyId,assetId,name,deptId,userId);
        assetUse.setNumStatus(1);
        assetUse.setTxtStatus("流转中");

        if (StringUtils.isNotEmpty(keyId)) {
            assetUseService.approve(assetUse, dutyService.get(curDutyId), comment);
        } else {
            assetUseService.commit(assetUse, "com.fz.us.oa.core.entity.com.AssetUse", dutyService.get(curDutyId));
        }

        if(assetUse.getProcessState().name().equals("Finished")){
            doFinished(assetUse);
        }

        rMap.put("message", "提交成功");
        rMap.put("state", "1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    //审批
    @RequestMapping(value = "approve", method = RequestMethod.POST)
    public Object approve(@CurrentUser User user, String keyId,  String curDutyId, String comment){
        Map<String,Object> rMap=new HashMap<String,Object>();
        AssetUse assetUse=assetUseService.get(keyId);
        assetUseService.approve(assetUse, dutyService.get(curDutyId), comment);

        if(assetUse.getProcessState().name().equals("Finished")){
            doFinished(assetUse);
        }

        rMap.put("message","提交成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    public void doFinished(AssetUse assetUse){
        assetUse.setDateApply(new Date());
        assetUse.setNumStatus(1);
        assetUse.setTxtStatus("已领用");
        assetUseService.update(assetUse);

        Asset asset = assetUse.getAsset();
        asset.setTxtStatus("使用中");
        asset.setUser(assetUse.getUser());
        asset.setUserName(assetUse.getUser().getName());
        asset.setUseDepartment(assetUse.getUseDepartment());
        assetService.update(asset);
    }

    /**
     * 退回
     * @return
     */
    @RequestMapping(value = "back", method = RequestMethod.POST)
    public Object back(@CurrentUser User user, String keyId,String curDutyId, String comment) {
        if (StringUtils.isNotEmpty(keyId)) {
            AssetUse assetUse=assetUseService.get(keyId);
            assetUseService.back(assetUse, dutyService.get(curDutyId), comment);
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message","退回成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }
    /**
     * 否决
     * @return
     */
    @RequestMapping(value = "deny", method = RequestMethod.POST)
    public Object deny(@CurrentUser User user, String keyId,String curDutyId, String comment) {
        if (StringUtils.isNotEmpty(keyId)) {
            AssetUse assetUse=assetUseService.get(keyId);
            assetUseService.deny(assetUse, dutyService.get(curDutyId), comment);
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message","否决成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    /**
     * 列表
     */
    @RequestMapping(value = "list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String, Object> list(@CurrentUser User user,
                                    String viewtype,
                                    @RequestParam(required = false) String assetId,
                                    JqGridPager pager,
                                    String parentId,
                                    @RequestJsonParam(value = "filters", required = false) JqGridFilter filters) {
        Company company = user.getCompany();
        // 排序
        Order order = Order.order("createTime", SearchEnum.OrderType.desc);

        SearchResultPaging searchResult = null;
        List<Rule> rules = getSearchFilterRules(pager.getSearch(), filters);
        rules.add(RuleHelper.eq("company", company));
        rules.add(RuleHelper.eq("state", BaseEnumManager.StateEnum.Enable));

        if (!StringUtils.isEmpty(assetId)) {
            rules.add(RuleHelper.eq("asset.id", assetId));
        }

        User thisUser=null;
        if(StringUtils.isNotEmpty(parentId)){
            thisUser=personnelInfoService.get(parentId).getUser();
        }
        if(thisUser!=null){
            rules.add(RuleHelper.eq("user", thisUser));
        }

        if(StringUtils.isNotEmpty(viewtype)) {
            if (viewtype.equals("1")) {
                //申请中
                searchResult = assetUseService.paging(null,rules,order,
                        "com.fz.us.oa.core.entity.com.AssetUse", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed},null);
            }else if(viewtype.equals("2")){
                //已领用
                rules.add(RuleHelper.eq("numStatus", 1));
                searchResult = assetUseService.paging(null,rules,order,
                        "com.fz.us.oa.core.entity.com.AssetUse", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished},null);
            }else if(viewtype.equals("3")){
                //本人使用+资产调拨
                rules.add(RuleHelper.or(
                        RuleHelper.eq("numStatus", 1),
                        RuleHelper.eq("numStatus", 2)));
                searchResult = assetUseService.paging(null,rules,order,
                        "com.fz.us.oa.core.entity.com.AssetUse", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished},null);
            }
        }else{
            //所有
            searchResult = assetUseService.paging(null,rules,order,
                    "com.fz.us.oa.core.entity.com.AssetUse", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished},null);
        }

        List<AssetUse> assetUseList = searchResult.getList();
        ArrayList<Map<String, Object>> dataRows = new ArrayList<Map<String, Object>>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;
        for(AssetUse assetUse: assetUseList){
            rMap = new HashMap<String, Object>();
            rMap.put("id", StringUtils.isEmpty(assetUse.getId())?"":assetUse.getId());

            if(assetUse.getCreateTime() != null){
                dateApply = assetUse.getCreateTime();
                rMap.put("year", yearFormat.format(dateApply));   // 年份
                rMap.put("month", monthFormat.format(dateApply));   // 月份
                rMap.put("dateApply",dateFormat.format(dateApply));
            } else {
                rMap.put("year", "");   // 年份
                rMap.put("month", "");   // 月份
                rMap.put("dateApply","");
            }

            asset = assetUse.getAsset();
            if(asset!=null){
                rMap.put("assetNo", asset.getAssetNo());
            }

            rMap.put("name", assetUse.getName());
            rMap.put("useDepartment", assetUse.getUseDepartment()==null?"": assetUse.getUseDepartment().getName());
            rMap.put("user", assetUse.getUser()==null?"": assetUse.getUser().getName());

            rMap.put("txtStatus", assetUse.getTxtStatus());
            rMap.put("purchaseMoney", assetUse.getAsset().getPurchaseMoney());
            rMap.put("brand", assetUse.getAsset().getBrand());
            rMap.put("model", assetUse.getAsset().getModel());

//        rMap.put("processStateName", entity.getProcessState()==null?"": entity.getProcessState().value());
//        rMap.put("createTime", entity.getCreateTime()==null?"": DataUtil.DateTimeToString(entity.getCreateTime()));
//        rMap.put("dateApply", entity.getDateApply()==null?"": DataUtil.DateTimeToString(entity.getDateApply()));
            dataRows.add(rMap);
        }
        data.put("dataRows", dataRows);
        data.put("page", searchResult.getPageNumber());
        data.put("rows", searchResult.getPageSize());
        data.put("records", searchResult.getTotalCount());
        data.put("total", searchResult.getPageCount());
        return data;
    }

    /**
     * 从人事信息进入资产信息
     */
    @RequestMapping(value = "toList",method = RequestMethod.GET,produces = MediaType.TEXT_HTML_VALUE)
    public String toList(Model model,String parentId){
        model.addAttribute("parentId", parentId);

        return "/main/menu/com/assetuse_in";
    }

    /**
     * 弹出归还确认对话框
     */
    @RequestMapping(value = "return/{keyId}", method = RequestMethod.GET)
    public String openDialog(@CurrentUser User user, Model model, @PathVariable String keyId) {
        model.addAttribute("keyId", keyId);
        return "/com/assetuse_return_dialog";
    }

    /**
     * 保存实际归还日期
     */
    @RequestMapping(value = "savereturn/{keyId}", method = RequestMethod.POST)
    public Object saveDialogReturn(@CurrentUser User user,@PathVariable String keyId, String datFactReturn) {
        AssetUse assetUse = assetUseService.get(keyId);

        if (StringUtils.isNotBlank(datFactReturn)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                assetUse.setDatFactReturn(sdf.parse(datFactReturn));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        Asset asset = assetUse.getAsset();
        asset.setUser(null);
        asset.setUseDepartment(null);
        asset.setUserName("");
        asset.setTxtStatus("空闲");
        assetService.update(asset);

        assetUse.setTxtStatus("已归还");
        return ajaxJson(assetUseService.saveEntity(assetUse));
    }

}
